import * as React from "react";
import {closest, findNodeByPosition} from "utils";

export let spaceState = false;
const $space = space();

function space() {
  const div = document.createElement('div')
  div.style.width = '100%'
  div.style.height = '1px'
  div.style.background = 'red'

  div.addEventListener('dragenter', stopEnter, false)
  div.addEventListener('dragleave', stopLeave, false)
  return div
}

export const stopEnter = (ev: any) => {
  ev.preventDefault();
  ev.stopPropagation();
  spaceState = false;
  console.log('onDragEnter: -> space')
}
export const stopLeave = (ev: any) => {
  ev.preventDefault();
  ev.stopPropagation();
  spaceState = true;
  console.log('onDragLeave: -> space')
}

export const removeSpace = (event: React.DragEvent <HTMLDivElement>) => {
  const node = closest(event.nativeEvent.target as HTMLElement, 'droppable');
  if ($space && node && node.contains($space) && $space.parentNode === node) {
    node.removeChild($space)
  }
}

export const insertSpace = (event: React.DragEvent <HTMLDivElement>) => {
  const node = closest(event.nativeEvent.target as HTMLElement, 'droppable');
  if (node && node.dataset.path) {
    console.log([node], node.dataset.path)
    const { id } = node.dataset
    const path = node.dataset.path.split('-');

    if ((window as any).__data && (window as any).__data.path === node.dataset.path) {
      return
    }
    if (path && path.length) {
      const { x, y } = event.nativeEvent;
      const __node = (findNodeByPosition(node, path, { x, y }) || null)

      if (!node.contains($space)) {
        node.insertBefore($space, __node as any)
      }
    }
  }
}